package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
)

type LoginController struct {
	beego.Controller
}

type JSONStruct struct {
	Code int
	Msg  string
}

func (this *LoginController) Get() {
	this.TplName = "login.html"
}

func (this *LoginController) Post() {

	uname := this.Input().Get("username")
	pwd := this.Input().Get("password")
	if beego.AppConfig.String("uname") == uname &&
		beego.AppConfig.String("pwd") == pwd {
		this.Ctx.SetCookie("uname", uname, 0, "/")
		this.Ctx.SetCookie("pwd", pwd, 0, "/")

		mystruct := &JSONStruct{1, "passwordIsOk!"}
		this.Data["json"] = &mystruct
		this.ServeJSON()
	}
	// this.Ctx.WriteString(beego.AppConfig.String("uname"))
	// this.Ctx.WriteString(fmt.Sprint(this.Input()))
	mystruct := &JSONStruct{0, fmt.Sprint(this.Input())}
	this.Data["json"] = &mystruct
	this.ServeJSON()
	return
}

func checkAccount(ctx *context.Context) bool {
	ck, err := ctx.Request.Cookie("uname")
	if err != nil {
		return false
	}
	uname := ck.Value
	ck, err = ctx.Request.Cookie("pwd")
	if err != nil {
		return false
	}
	pwd := ck.Value
	return beego.AppConfig.String("uname") == uname &&
		beego.AppConfig.String("pwd") == pwd
}
